import Vue from 'vue'
import VueRouter from 'vue-router'
const LoginIndex = () => import ('@/views/login/index.vue')
const Layout = () => import ('@/views/layout/Layout.vue')
const Home = () => import ('@/views/home/home.vue')
const Video = () => import('@/views/video/video.vue')
const Question = () => import ('@/views/question/question.vue')
const My = () => import ('@/views/my/my.vue')
const Search = () => import('@/views/search')
const SearchList = () => import ('@/views/search/searchList')
const ArticleDesc = () => import ('@/views/article')
const MyProfile = () => import ('@/views/my/profile.vue')
const MyChat = () => import ('@/views/my/chat.vue')

import store from '@/store'
Vue.use(VueRouter)
// 将原型的方法存到一个变量中
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const router = new VueRouter({
  routes: [
    { path: '/login', component: LoginIndex },
    { path: '/', component: Layout, children: [
      { path: '', component: Home, meta: { isKeepAlive: true }},
      { path: 'video', component: Video },
      { path: 'question', component: Question },
      { path: 'my', component: My }
    ] },
    { path: '/search', component: Search },
    { path: '/searchList', component: SearchList },
    { path: '/articleDesc/:id', component: ArticleDesc },
    { path: '/userProfile', component: MyProfile },
    { path: '/userChat', component: MyChat }

  ]
})
// 需要认证的页面
const Authurls = ['/my']
router.beforeEach((to, from, next) => {
  const token = store.state.user.tokenInfo.token
  // 如果去 的是/login, 判断 token 存不存在, 如果 token 存在说明登录过了, 直接跳转到首页
  if (to.path === '/login' && token) {
    next('/')
    return
  }
  // 如果需要授权的页面
  if (Authurls.includes(to.path)) {
    // 如果token存在
    if (token) {
      next()
    } else {
      router.push({
        path: '/login',
        query: {
          backto: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})
export default router
